package com.wl.mvi

import android.os.Bundle
import android.util.Log
import android.webkit.WebView
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.wl.lib.arouter.ARouterConstant
import com.wl.lib.mvi.BaseBindingActivity
import com.wl.mvi.databinding.ActivityMainBinding
import com.wl.mvi.home.HomeFragment
import com.wl.mvi.main.fragment.BlogFragment
import com.wl.mvi.main.fragment.MeFragment
import com.wl.mvi.main.fragment.ProjectFragment
import com.wl.mvi.main.fragment.SearchFragment

@Route(path = ARouterConstant.App.MAIN)
class MainActivity : BaseBindingActivity<ActivityMainBinding>() {

    companion object {
        private const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        WebView.setWebContentsDebuggingEnabled(true)
        binding.bottomNavView.setOnItemSelectedListener {
            Log.d(TAG, "bottomNavView click $it")
            when(it.itemId) {
                R.id.navigation_home -> switchFragment(0)
                R.id.navigation_blog -> switchFragment(1)
                R.id.navigation_search -> switchFragment(2)
                R.id.navigation_project_type -> switchFragment(3)
                R.id.navigation_me -> switchFragment(4)
            }
            true
        }

        initViewPager()
    }

    private fun switchFragment(position: Int) = binding.mainViewPager.setCurrentItem(position, false)

    private fun initViewPager() {
        binding.mainViewPager.isUserInputEnabled = false
        binding.mainViewPager.offscreenPageLimit = 2 // 这样能保证 5个 fragment 不 onDestroy, 如果需要及时刷新的数据可以放到 onResume 中
        binding.mainViewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = 5

            override fun createFragment(position: Int) = when(position) {
                0 -> HomeFragment()
                1 -> BlogFragment()
                2 -> SearchFragment()
                3 -> ProjectFragment()
                4 -> MeFragment()
                else -> HomeFragment()
            }
        }
    }
}
